package org.rafal.springframework.service.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.rafal.springframework.domain.App_User;
import org.rafal.springframework.service.App_UserService;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("app_UserService")
@Repository
@Transactional
public class App_UserServiceImpl implements App_UserService{

	private Log log = LogFactory.getLog(App_UserServiceImpl.class);

	@PersistenceContext
	private EntityManager em;
	
	@Transactional(readOnly=true)
	public List<App_User> findAll() {
		return em.createNamedQuery("App_User.findAll", App_User.class)
				.getResultList();
	}

	@Transactional(readOnly=true)
	public App_User findById(Long id) {
		TypedQuery<App_User> typedQuery = em.createNamedQuery(
				"App_User.findById", App_User.class);
		typedQuery.setParameter("id", id);
		return typedQuery.getSingleResult();
	}

	// Save or update user
	public App_User save(App_User user) {
		if (user.getId() == null) {
			log.info("Inserting new user.");
			em.persist(user);
		} else {
			em.merge(user);
			log.info("Updating user with id " + user.getId());
		}
		log.info("Inserted user with id" + user.getId());
		return user;
	}

	public void delete(App_User user) {
		App_User deleteUser = em.merge(user);
		em.remove(deleteUser);
		log.info("User with id: " + user.getId() + " deleted successfully.");
	}

	final static String FindAllByNativeQuery = "Select ID,VERSION,NAME,SURNAME,JOINDATE,IDGRUPY from APP_USER";

	@Transactional(readOnly = true)
	public List<App_User> findAllByNativeQuery() {
		return em.createNamedQuery(FindAllByNativeQuery, App_User.class).getResultList();
	}

	@Transactional(readOnly=true)
	public List<App_User> findByFirstName(String firstName) {
		TypedQuery<App_User> typedQuery = em.createNamedQuery(
				"select a from App_User a where a.name = :name", App_User.class);
		typedQuery.setParameter("name", firstName);
		return typedQuery.getResultList();
	}

}
